package com.njxr.web.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 跨域设置
 *
 * @author wangyue
 * @date 2021/8/16 12:31
 */
@Slf4j
@Configuration
public class GlobalCorsConfiguration {

    @Bean
    public FilterRegistrationBean<CorsFilter> myCorsFilter() {
        log.info("================跨域设置====================");
        CorsConfiguration config = new CorsConfiguration();
        //允许跨域的域名。*：代表所有域名都可以跨域访问
        //多个源域名时，可以继续使用add来添加
        config.addAllowedOrigin("*");
        //允许携带cookie
        config.setAllowCredentials(true);
        //代表所有的请求方法：GET、POST、PUT、DELETE....
        config.addAllowedMethod("*");
        //允许携带任何头信息
        config.addAllowedHeader("*");
        config.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // CORS 配置对所有接口都有效
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<CorsFilter>(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }

}